package com.itheima.config;


import com.itheima.controller.backend.security.SpringSecurityUserService;
import com.itheima.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;

@Slf4j
public class SpringAuthenticationProvider implements AuthenticationProvider {
    private PasswordEncoder passwordEncoder;

    // 假设这是一个用户服务接口，用于验证用户名和密码
    private SpringSecurityUserService springSecurityUserService;

    public SpringAuthenticationProvider(PasswordEncoder passwordEncoder, SpringSecurityUserService springSecurityUserService) {
        this.passwordEncoder = passwordEncoder;
        this.springSecurityUserService = springSecurityUserService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        String encodedPassword = passwordEncoder.encode(password);
        log.info("密码："+ encodedPassword);
        User user = (User) springSecurityUserService.loadUserByUsername(username);
        if (user == null) {
            // 用户不存在
            log.info("用户不存在");
            throw new AuthenticationException("用户不存在") {};
        }

        // 使用PasswordEncoder比较密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            // 密码错误
            log.info("密码错误");
            throw new AuthenticationException("密码错误") {};
        }

        // 密码验证通过，创建Authentication对象
        return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
